<template>
  <div class="app-container df-col">
    <!--搜索、按钮区-->
    <div class="action-wrap df bb1">
      <i class="back iconfont icon-start fs30" :class="{'cAAA': !canBack}" title="返回上一目录" @click="back"></i>
      <i class="iconfont icon-start fs30" :class="{'cAAA': !canForward}" title="前进" @click="forward"></i>
      <div class="search-wrap df1">
        <form action="#" @submit.prevent="search">
          <div class="search df-center b1">
            <i class="iconfont icon-magnifier fs20"></i>
            <input type="text" class="df1" v-model="keywords" @input="search">
          </div>
        </form>
      </div>
      <i class="iconfont icon-refresh-circle fs30" title="刷新目录" @click="getAllList"></i>
      <i class="iconfont icon-add fs30 theme-color" title="新建文件夹" @click="openFolderForm"></i>
      <i class="iconfont icon-business-server fs30" title="设置" @click="openSettingForm"></i>
    </div>

    <div class="main df df1 bcFFF">
      <!--上一页-->
      <div class="left br1 df-center candrag"
           title="上一页"
           @click="prevPage"
           @drop.prevent="clearDragPageTimer" @dragover.prevent="DOPage('prev')"
           @dragleave.prevent="clearDragPageTimer">
        <i class="iconfont icon-left fs50" :class="[canPrev ? 'theme-color' : 'c999']"></i>
      </div>

      <!--文件夹操作区-->
      <div class="center df1 df-col">

        <!--路径显示区-->
        <div class="root df"><span class="df1">{{path}}</span><span class="open-btn" @click="openPath">打开</span></div>

        <!--文件夹列表-->
        <div class="df1 folder-list scroll-con candrag" v-loading="loading" @drop.prevent="onDropInCurrentPath" @dragover.prevent="" @dragleave.prevent="">
          <ul class="" v-show="!loading">
            <folder-item v-for="(item, index) in currentFolderList"
                         :info="item"
                         :path="path"
                         @dblclick.native="openFolder(item)"></folder-item>
          </ul>

          <!--no-result-->
          <div class="no-result candrag" v-show="!currentFolderList.length && !loading">
            <img src="../assets/images/no-result.png" alt="">
            <div class="c666">没有内容</div>
          </div>
        </div>
      </div>

      <!--下一页-->
      <div class="right bl1 df-center candrag"
           title="下一页"
           @click="nextPage"
           @drop.prevent="clearDragPageTimer"
           @dragover.prevent="DOPage('next')"
           @dragleave.prevent="clearDragPageTimer">
        <i class="iconfont icon-right fs50" :class="[canNext ? 'theme-color' : 'c999']"></i>
      </div>
    </div>

    <!--文件暂存区-->
    <div class="footer bcFFF candrag" v-show="showTempArea" @drop.prevent="onTempAreaDrop" @dragover.prevent="" @dragleave.prevent="">
      <!--no-result-->
      <div class="no-result df-center df-col" v-show="!fileTempList.length">
        <span class="iconfont icon-cloud fs50 theme-color"></span>
        <div>暂存区</div>
      </div>

      <div class="list df" v-show="fileTempList.length">
        <div class="btn all-del-btn" @click="tempAllDel">全部移除</div>
        <div class="btn all-add-btn" @click="tempAllAdd">全部加入</div>
        <ul class="df df1">
          <file-item v-for="(item, index) in fileTempList"
                     :key="item.path"
                     :index="index"
                     :item="item"
                     :path="path"
                     @delFile="delFileTemp"
                     @addFile="getAllList"></file-item>
        </ul>
      </div>
    </div>

    <!--新建文件夹-->
    <folder-form ref="folderForm" :path="path" @submit="createFolder"></folder-form>
    <!--设置表单-->
    <setting-form ref="settingForm"></setting-form>
  </div>
</template>

<style lang="scss" scoped>
  .action-wrap {
    width: 100%;
    overflow-x: hidden;
    box-sizing: border-box;
    flex-wrap: wrap;
    padding: 5px;
    .iconfont {
      padding: 0 10px;
      cursor: pointer;
    }
    .icon-start.back {
      transform: rotate(180deg);
    }
    .search-wrap {
      /*padding: 0 40px;*/
      .search {
        height: 30px;
        padding-right: 20px;
        border-radius: 50px;
        background-color: #f6f6f6;
        input {
          border: 0;
          outline: 0;
          background-color: transparent;
        }
      }
    }

  }

  .main {
    .left, .right {
      width: 60px;
      background: linear-gradient(-45deg, #f8f8f8 25%, #ffffff 0,#ffffff 50%,#f8f8f8 0%,#f8f8f8 75%,#ffffff 0);
      background-size: 10px 10px;
      cursor: pointer;
      i {
        transition: all .2s ease;
      }
      &:hover {
        i {
          font-size: 60px;
        }
      }
    }
    .left {
      i.c999 {
        text-shadow: 4px 0px 3px rgba(153, 153, 153, 0.5);
      }
      i.theme-color {
        text-shadow: 4px 0px 3px rgba(34, 215, 187, 0.5);
      }
    }
    .right {
      i.c999 {
        text-shadow: -4px 0px 3px rgba(153, 153, 153, 0.5);
      }
      i.theme-color {
        text-shadow: -4px 0px 3px rgba(34, 215, 187, 0.5);
      }
    }

    .center {
      .root {
        padding: 5px 13px;
        background-color: rgba(255, 196, 66, 0.2);
        color: #ffc442;
        letter-spacing: 1px;
        .open-btn {
          font-size: 14px;
          text-decoration: underline;
          cursor: pointer;
        }
      }
      .folder-list {
        overflow-y: auto;
        position: relative;
        .no-result {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          width: 70px;
          img  {
            width: 100%;
          }
          div {
            margin-top: 5px;
            text-align: center;
          }
        }
        ul {}
      }
    }
  }

  .footer {
    /*height: 150px;*/
    border-top: 5px dotted $border;
    & > div {
      width: 100%;
      height: 100%;
      overflow-x: auto;
      overflow-y: hidden;
    }

    .no-result {
      padding: 10px 0;
    }

    .list {
      .btn {
        padding: 10px;
        writing-mode: vertical-lr;
        color: #ffffff;
        text-align: center;
        letter-spacing: 5px;
        cursor: pointer;
        border-right: 1px solid $border;
      }
      .all-del-btn {
        background-color: rgba(255, 0, 0, 0.7);
      }
      .all-add-btn {
        background-color: rgba(34, 215, 187, 0.7);
      }
      ul {
        height: 100%;
        box-sizing: border-box;
        padding: 20px 30px;
        white-space: nowrap;
        overflow: auto;
      }
    }
  }
</style>


<script>
  import fileItem from '../components/fileItem'
  import folderItem from '../components/FolderItem'
  import folderForm from './folderForm'
  import {mapGetters, mapActions} from 'vuex'
  import dragMixin from '../components/dragMixin.js'
  import {shell} from 'electron'
  import settingForm from './settingForm'

  export default {
    mixins: [dragMixin],
    name: "home",
    components: {
      fileItem,
      folderItem,
      folderForm,
      settingForm,
    },
    data () {
      return {
        path: '',                 //  当前路径
        directoryHistory: [],     //  路径切换历史记录
        historyPoint: 0,          //  历史记录指针
        directoryHistoryObj: {
          go: (path) => {
            this.directoryHistory = this.directoryHistory.slice(0, this.historyPoint + 1)
            this.directoryHistory.push(path)

            if (this.directoryHistory.length == 1) {
              this.historyPoint = 0
            } else {
              this.historyPoint++
            }

            this.path = path
          },
          back: () => {
            if (this.historyPoint > 0) {
              this.historyPoint--
            }

            this.path = this.directoryHistory[this.historyPoint]
          },
          forward: () => {
            if (this.historyPoint < this.directoryHistory.length) {
              this.historyPoint++
            }

            this.path = this.directoryHistory[this.historyPoint]
          },
          reset: () => {
            this.directoryHistory = [this.setting.rootPath]
            this.historyPoint     = 0
          }
        },

        folderList: [],           //  文件列表
        currentFolderList: [],    //  当前页文件列表
        keywords: '',             //  搜索关键字
        pageNo: 1,
        loading: false,

        fileTempList: this.$db.get('fileTempList').value(),         //  暂存区文件列表

        prevTimer: null,          //  拖拽翻页的定时器
        nextTimer: null,          //  拖拽翻页的定时器
      }
    },
    computed: {
      ...mapGetters(['setting']),
      showTempArea () {   //  是否显示 暂存区
        return this.setting.showTempArea
      },
      canPrev () {  //  可以前往上一页
        if (this.pageNo == 1 || !this.folderList.length) {
          return false
        }

        return true
      },
      canNext () {  //  可以前往下一页
        if (this.currentFolderList.length < this.setting.pageSize) {
          return false
        }

        return true
      },
      canBack () {    //  可以返回上一目录
        return this.historyPoint > 0
      },
      canForward () {
        if (this.directoryHistory.length <= 1) {
          return false
        }

        return this.historyPoint != (this.directoryHistory.length - 1)
      }
    },
    watch: {
      setting (newVal, oldVal) {
        if (newVal.rootPath != oldVal.rootPath) {
          this.directoryHistoryObj.reset()
          this.path = newVal.rootPath
        } else if (newVal.pageSize != oldVal.pageSize) {
          this.getAllList()
        }
      },
      path (newVal) {
        if (newVal) {
          this.getAllList()
        }
      },
      fileTempList (newVal) {
        let arr = this.$utils.formatFileObj(newVal)
        this.$db.set('fileTempList', arr).write()
      }
    },
    methods: {
      forward () {
        if (!this.canForward) {
          return
        }

        this.directoryHistoryObj.forward()
      },
      //  返回上一目录
      back () {
        if (!this.canBack) {
          return
        }

        this.directoryHistoryObj.back()
      },
      //  打开新建文件夹对话框
      openFolderForm () {
        this.$refs.folderForm.openDialog()
      },
      //  新建文件夹成功
      createFolder (name) {
        this.openFolder({
          isDirectory: true,
          name: name,
        })
      },
      //  前往设置页面
      openSettingForm () {
        this.$refs.settingForm.openForm()
      },
      //  打开当前路径
      openPath () {
        shell.openItem(this.path)
      },

      //  搜索
      search () {
        this.loadFirstPage(this.keywords)
      },
      //  得到当前目录的所有文件列表，并显示第一页数据
      getAllList () {
        let list = this.$fs.readdirSync(this.path)
        let arr = []

        Array.from(list).forEach(item => {
          let obj = {
            isDirectory: false,
            name: item
          }
          try {
            let state = this.$fs.statSync(this.path + item)
            if (state && state.isDirectory()) {
              obj.isDirectory = true
            }
            obj.state = state

            arr.push(obj)
          } catch (e) {}
        })

        this.folderList = arr
        this.keywords = ''
        this.loadFirstPage()
      },
      //  加载第一页
      loadFirstPage (keywords) {
        this.pageNo = 1
        this.loadData(keywords)
      },
      //  加载当前页数据
      loadData (keywords) {
        this.loading = true

        let start = this.pageNo == 1 ? 0 : ((this.pageNo - 1) * this.setting.pageSize)
        let end   = this.pageNo * this.setting.pageSize
        let list  = this.folderList

        if (keywords) {     //  search
          let regStr = `[${keywords}]`
          let reg = new RegExp(regStr, 'g');

          list = list.filter(item => {
            let regMatch = item.name.match(reg)
            return regMatch
          })
        }

        this.currentFolderList = list.slice(start, end)

        setTimeout(() => {
          this.loading = false
        }, 300)
      },
      //  上一页
      prevPage () {
        if (!this.canPrev) {
          return
        }

        this.pageNo--
        this.loadData()
      },
      //  下一页
      nextPage () {
        if (!this.canNext) {
          return
        }

        this.pageNo++
        this.loadData()
      },
      //  清楚拖拽翻页定时器
      clearDragPageTimer () {
        clearInterval(this.prevTimer)
        clearInterval(this.nextTimer)
        this.prevTimer = null
        this.nextTimer = null
      },
      //  拖拽翻页
      DOPage (type) {
        if (type == 'prev') {
          if (!this.prevTimer) {
            this.prevTimer = setInterval(() => {
              this.prevPage()
            }, 800)
          }
        }

        if (type == 'next') {
          if (!this.nextTimer) {
            this.nextTimer = setInterval(() => {
              this.nextPage()
            }, 800)
          }
        }
      },

      //  双击更改当前路径 以达到打开文件夹的效果
      openFolder (item) {
        if (!item.isDirectory) {
          return
        }

        this.directoryHistoryObj.go(this.path + item.name + '\\')
      },
      //  拖拽文件至当前文件夹
      onDropInCurrentPath (e) {
        let files = e.dataTransfer.files
        this.dropMultFiles(files, this.path)
      },

      //  拖拽文件进入 暂存区
      onTempAreaDrop (e, arr) {
        if (!this.path) {
          return
        }

        let files = arr || Array.from(e.dataTransfer.files)
        let newFiles = []

        files.forEach(file => {
          let type = file.name.split('.').pop().toLowerCase()
          file._type = type
          // if (file.type && file.type.indexOf('video') < 0) {
            newFiles.push(file)

            this.fileTempList = this.fileTempList.filter(item => {
              if (item.path == file.path) {
                return false
              }
              return true
            })
          // }

        })

        this.fileTempList = newFiles.concat(this.fileTempList)
      },
      //  拖拽区的删除文件
      delFileTemp (index) {
        this.fileTempList.splice(index, 1)
      },
      //  拖拽区全部移除
      tempAllDel () {
        this.$confirm('此操作将移除暂存区所有文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.fileTempList = []
        }).catch(() => {
        });
      },
      //  拖拽区全部加入
      tempAllAdd () {
        this.$confirm(`将暂存区所有文件复制到${this.path}, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.dropMultFiles(this.fileTempList, this.path).then(() => {
            this.fileTempList = []
          })
        }).catch(() => {
        });
      }
    },
    mounted () {
      this.path = this.setting.rootPath

      if (this.path) {
        this.directoryHistoryObj.reset()
      } else {
        this.openSettingForm()
      }

      this.$electron.ipcRenderer.on('drag-file-from-mini', (event, e) => {
        this.onTempAreaDrop(null, e)
      });
    }
  }
</script>
